package com.wyw.hemerocallis.service;

import com.alibaba.fastjson.JSON;
import com.wyw.hemerocallis.entity.HemerocallisLogistics;
import com.wyw.hemerocallis.order.LogisticsMessage;
import com.wyw.hemerocallis.repository.HemerocallisLogisticsRepository;
import com.wyw.hemerocallis.sink.LogisticsSink;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.messaging.handler.annotation.Payload;

/**
 * 物流服务实现
 *
 * @author Mr Wu    yewen.wu.china@gmail.com
 * <p>
 * Update History:
 * Author        Time            Content
 */
@Slf4j
@EnableBinding(LogisticsSink.class)
@RequiredArgsConstructor
public class LogisticsServiceImpl {
    private final HemerocallisLogisticsRepository logisticsRepository;

    /**
     * 订阅监听订单微服务发送的物流消息
     */
    @StreamListener("logisticsInput")
    public void consumeLogisticsMessage(@Payload Object payload) {
        log.info("receive and consume logistics message: [{}]", payload.toString());
        LogisticsMessage logisticsMessage = JSON.parseObject(payload.toString(), LogisticsMessage.class);

        HemerocallisLogistics logistics = logisticsRepository.save(
                new HemerocallisLogistics(
                        logisticsMessage.getUserId(),
                        logisticsMessage.getOrderId(),
                        logisticsMessage.getAddressId(),
                        logisticsMessage.getExtraInfo()
                )
        );
        log.info("consume logistics message success: [{}]", logistics.getId());
    }
}
